package com.study.controller;

import com.study.utils.SysUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @author zhuzi
 * 2024/2/26 13:43
 */
@Slf4j
@RestController
@RequestMapping("abc")

public class AbcController {

    @Resource
    HttpServletRequest request;

    @RequestMapping("timeout")
    public LocalDateTime timeout() throws InterruptedException {
        log.info("{}",getBaseUrl(request));
        log.info("{}",getWebPathSpring());
        log.info("getContextPath|{}",request.getContextPath());
        log.info("getServletContext|{}",request.getServletContext().getContextPath());
        log.info("{}",request.getSession().getServletContext().getContextPath());


        TimeUnit.SECONDS.sleep(2);
        return LocalDateTime.now();
    }

    public static String getBaseUrl(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getSession().getServletContext().getContextPath()).append("/").toString();
    }

    /**
     * 得到网络路径
     *
     * @return {@link String}
     */
    public static String getWebPathSpring() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        ServletUriComponentsBuilder contextPath = ServletUriComponentsBuilder.fromContextPath(request);
        return contextPath.toUriString();
    }

}
